<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主题卡片区 -->
    <el-card>
      <!-- 添加区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showaddDialog">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <tree-table
        :data="CategoriesList"
        :columns="columns"
        :tree-type="true"
        children-prop="children"
        border
        :show-row-hover="false"
        :expand-type="false"
        :selection-type="false"
        show-index
        index-text="#"
      >
        <!-- 是否有效插槽 -->
        <template slot-scope="scope" slot="isOK">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted===false"
            style="color:green;fontSize:24px"
          ></i>
          <i class="el-icon-error" v-else style="color:red;fontSize:24px"></i>
        </template>
        <!-- 等级插槽 -->
        <template slot-scope="scope" slot="level">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作插槽 -->
        <template slot="opt" slot-scope="scope">
          <!-- slot-scope="scope"  -->
          <!-- <i>{{ scope.row.cat_id}}</i> -->
          <el-button type="primary" icon="el-icon-edit" @click="getEditCate(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listInfo.pagenum"
        :page-sizes="[10, 50, 100, 300]"
        :page-size="listInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="closeAddDialogVisible"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类:">
            <el-cascader
              v-model="selectKeys"
              :options="parentCategoriesList"
              :props="cascaderProp"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAddCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closeEditDialogVisible"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="分类名称:" prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
          <!-- <el-form-item label="父级分类:">
            <el-cascader
              v-model="selectKeys"
              :options="parentCategoriesList"
              :props="cascaderProp"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      CategoriesList: [], // 所有商品分类列表
      listInfo: {
        type: [3],
        pagenum: 1, // 当前页
        pagesize: 10 // 每页多少条数据
      },
      total: 0,
      // tree-table的配置
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isOK'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      addDialogVisible: false,
      addForm: {
        cat_pid: 0, // 默认添加的父级分类为一级
        cat_name: '',
        cat_level: 0 // 默认添加的分类等级为一级
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      parentCategoriesList: [], // 父级分类列表
      cascaderProp: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true // 设置父子节点取消选中关联，从而达到选择任意一级选项的目的。
      },
      selectKeys: [],
      editDialogVisible: false,
      editForm: {
        cat_name: ''
      },
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      cateID: ''
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    // 获取商品分类列表
    async getCategoriesList() {
      // 发送请求，获取商品列表数据
      const res = await this.$http.get('categories', { params: this.listInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.CategoriesList = res.data.result
      this.total = res.data.total
      // console.log(res)
    },
    // 获取每页多少条数据
    handleSizeChange(val) {
      this.listInfo.pagesize = val
      this.getCategoriesList()
    },
    // 获取当前页码
    handleCurrentChange(val) {
      this.listInfo.pagenum = val
      this.getCategoriesList()
    },
    // 获取所有父级分类的信息 1级和2级
    async getParentList() {
      // 获取所有父级分类的信息 1级和2级
      const res = await this.$http.get('categories', { params: { type: 2 } })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 获取列表成功，将信息赋值给父级分类列表数组
      this.parentCategoriesList = res.data
    },
    async showaddDialog() {
      this.getParentList()
      this.addDialogVisible = true
    },
    handleChange(val) {
      this.selectKeys = val
      // console.log(val)
      if (val.length > 0) {
        this.addForm.cat_pid = val[val.length - 1] // 父类 id
        this.addForm.cat_level = val.length // 添加分类的等级，如果有父类，则添加的为父类数组的长度， 0表示一级分类；1表示二级分类；2表示三级分类
      } else {
        // 没有选择父类等级，添加的为一级分类
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
      // console.log(this.addForm.cat_pid)
      // console.log(this.addForm.cat_level)
    },
    // 关闭添加分类对话框触发close事件
    closeAddDialogVisible() {
      this.$refs.addFormRef.resetFields()
      this.selectKeys = []
    },
    // 发送请求，添加分类
    saveAddCate() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) {
          return this.$message.error('分类名称不符合规则')
        } else {
          // 发送请求
          const res = await this.$http.post('categories', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getCategoriesList()
        }
      })
      this.addDialogVisible = false
    },
    // 展示编辑分类信息
    getEditCate(cateInfo) {
      console.log(cateInfo)
      this.editForm.cat_name = cateInfo.cat_name // 展示选中的分类名称
      this.cateID = cateInfo.cat_id
      // 展示所有分类的父类信息和父类分类列表
      // if (cateInfo.cat_pid === '0') {
      //   // 没有父级，则父类不展示
      //   return
      // }
      // this.selectKeys.push(cateInfo.cat_pid)
      // this.getParentList()
      this.editDialogVisible = true
    },
    // 保存编辑分类
    saveEditCate() {
      // 验证是否通过
      this.$refs.editFormRef.validate(async val => {
        if (!val) {
          return this.$message.error('分类名称不符合规则')
        } else {
          const res = await this.$http.put(
            'categories/' + this.cateID,
            this.editForm
          )
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getCategoriesList()
        }
      })
      this.editDialogVisible = false
    },
    closeEditDialogVisible() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除分类
    async deleteCate(id) {
      const result = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result, id)
      if (result !== 'confirm') return this.$message.info('已取消删除')
      // 发送请求，删除该分类
      const res = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCategoriesList()
    }
  }
}
</script>
<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
}
</style>
